﻿using System;
using System.Windows;
using System.Windows.Navigation;
using System.Windows.Threading;
using BathroomLocator.Phone.Models;
using Microsoft.Phone.Shell;
using Microsoft.Samples.WindowsPhoneCloud.StorageClient;

namespace BathroomLocator.Phone.ViewModel
{
	public class BathroomListPageViewModel : TableBaseViewModel<BathroomLocation>
	{
		private const string IconsRootUri = "/Toolkit.Content/";

		private readonly ICloudTableClient cloudTableClient;
		private static bool tableCreated = false;

		public BathroomListPageViewModel()
			: this(App.CloudClientFactory, Deployment.Current.Dispatcher)
		{}

		public BathroomListPageViewModel(ICloudClientFactory cloudClientFactory, Dispatcher dispatcher)
			: base(cloudClientFactory, dispatcher)
		{
			this.cloudTableClient = cloudClientFactory.ResolveCloudTableClient(this.TableName);
		}
		
		public event EventHandler<NavigationEventArgs> Navigate;

		public ICloudTableClient CloudTableClient
		{
			get
			{
				return this.cloudTableClient;
			}
		}

		public override string TableName
		{
			get { return "BathroomLocation"; }
		}

		public void NavigateTo(Uri navigationUri)
		{
			this.RaiseNavigate(navigationUri);
		}

		private void RaiseNavigate(Uri navigationUri)
		{
			var navigate = this.Navigate;
			if (navigate != null)
			{
				navigate(this, new NavigationEventArgs(null, navigationUri));
			}
		}

		protected override void PopulateApplicationBarButtons(Microsoft.Phone.Shell.IApplicationBar applicationBar)
		{
			var refreshButton = new ApplicationBarIconButton(new Uri(string.Format("{0}{1}", IconsRootUri, "appbar.refresh.rest.png"), UriKind.Relative)) { Text = "refresh" };
			refreshButton.Click += (s, e) => this.LoadTable();

			var addButton = new ApplicationBarIconButton(new Uri(string.Format("{0}{1}", IconsRootUri, "appbar.add.rest.png"), UriKind.Relative)) { Text = "add row" };
			addButton.Click += (s, e) => this.RaiseNavigate(new Uri("/Pages/BathroomLocationDetailsEditPage.xaml?editData=false", UriKind.Relative));

			applicationBar.Buttons.Add(refreshButton);
			applicationBar.Buttons.Add(addButton);
		}

		public override void LoadTable()
		{
            // Not going to create the table from the phone.  The service should be taking care of the table create on role startup.
			base.LoadTable();
		}
	}
}
